package cn.xiongxf.pet.service.impl;

import cn.xiongxf.basic.domain.Point;
import cn.xiongxf.basic.exception.BusinessException;
import cn.xiongxf.basic.service.IBaiduAiAuditService;
import cn.xiongxf.basic.util.*;
import cn.xiongxf.order.domain.OrderPetAcquisition;
import cn.xiongxf.order.mapper.OrderPetAcquisitionMapper;
import cn.xiongxf.org.domain.Employee;
import cn.xiongxf.org.domain.Shop;
import cn.xiongxf.org.mapper.EmployeeMapper;
import cn.xiongxf.org.mapper.ShopMapper;
import cn.xiongxf.pet.domain.Pet;
import cn.xiongxf.pet.domain.SearchMasterMsg;
import cn.xiongxf.pet.domain.SearchMasterMsgAuditLog;
import cn.xiongxf.pet.mapper.PetMapper;
import cn.xiongxf.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.xiongxf.pet.mapper.SearchMasterMsgMapper;
import cn.xiongxf.pet.query.SearchMasterMsgQuery;
import cn.xiongxf.pet.service.ISearchMasterMsgService;
import cn.xiongxf.basic.service.impl.BaseServiceImpl;
import cn.xiongxf.user.domain.Logininfo;
import cn.xiongxf.user.domain.User;
import cn.xiongxf.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;  // service中不仅可以注入mapper，还能注入其它service
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;


    @Transactional  // (noRollbackFor=CommonException.class)
    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        // id         - 自增长
        // name       - 来自页面
        // age        - 来自页面
        // gender     - 来自页面
        // coat_color - 来自页面
        // resources  - 来自页面
        // pet_type   - 来自页面
        // price      - 来自页面
        // address    - 来自页面
        // title      - 来自页面
        // state      - 来自实体默认值  // 0待审核或驳回， 1表示已审核待处理，2表示处理成功，3拒
        // user_id    - 谁发布的寻主消息 = 用户 = 登录了才能发布
        // shop_id    - 获取最近的门店的id - 审核通过后设置

        // 获取发布寻主消息的用户
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());

        // 1.添加user_id并保存寻主消息表
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);

        // 2.百度智能审核
        Boolean textBoo = baiduAiAuditService.textAudit(searchMasterMsg.getTitle() + searchMasterMsg.getName() + searchMasterMsg.getAddress());
        Boolean imageBoo = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());

        if(textBoo && imageBoo){
            // 3.百度智能审核通过
            // 3.1.添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setState(1);
            log.setMsgId(searchMasterMsg.getId());
            log.setNote("审核通过");
            log.setAuditTime(new Date());
            // audit_id不管，因为没有人工审核
            searchMasterMsgAuditLogMapper.save(log);

            // 3.2.添加寻主信息表的数据
            // 改状态：state = 1
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核通过");

            // 获取最近的店铺
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point,shopMapper.loadAll());

            if (nearestShop != null){
                // 保存shop_id信息
                searchMasterMsg.setShopId(nearestShop.getId());

                // 给店铺管理员发短信或邮件，通知他到指定的address去收购宠物
                //SmsUtils.sendSms(nearestShop.getTel(),"你有新的订单，请尽快处理：" + searchMasterMsg.getTitle());
                System.out.println("你有新的订单，请尽快处理：" + searchMasterMsg.getTitle());
            }

            // 更新寻主消息表到数据库
            searchMasterMsgMapper.update(searchMasterMsg);

            return new AjaxResult();
            // （如果没有符合条件的店铺，不用管）
        }else {
            // 4.审核失败
            // 4.1.添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setState(0);
            log.setMsgId(searchMasterMsg.getId());
            log.setNote("审核失败，内容非法");
            log.setAuditTime(new Date());
            // audit_id不管，因为没有人工审核
            searchMasterMsgAuditLogMapper.save(log);

            // 4.2.添加并保存寻主信息表的数据
            searchMasterMsg.setState(0);
            searchMasterMsg.setNote("审核失败，内容非法");
            searchMasterMsgMapper.save(searchMasterMsg);

            // 4.3.返回异步结果
            return new AjaxResult(false,"审核失败，内容非法");

        }

    }

    @Override
    public PageList<SearchMasterMsg> userQuery(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 获取用户的id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPageList(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 判断一个管理员是店铺管理员还是平台管理员
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        // 如果是店铺管理员就设置店铺id
        if(employee.getShop_id()!=null){//当前管理员是店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPageList(query);
    }

    @Override
    public void reject(Long id) {
        // 通过id将shopId置为null
        searchMasterMsgMapper.updateShopId(id);
    }

    @Override
    public void accept(Map<String, String> map) {
        long msgId = Long.parseLong(map.get("msgId"));
        long handler = Long.parseLong(map.get("handler"));
        String note = map.get("note");
        // 1.校验：校验当前寻主消息是否有订单 - 有就说明当前寻主消息正在处理
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(msgId);
        if(order != null){
            throw new BusinessException("当前寻主消息正在处理，请勿重复接单!!!");
        }

        // 2.生成宠物保存到数据库
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = msg2Pet(msg);
        petMapper.save(pet);

        // 3.生成收购订单 - 发短信或邮件告诉店铺人员去收回宠物
        OrderPetAcquisition tempOrder = createOrder(msg,pet,handler,note);
        orderPetAcquisitionMapper.save(tempOrder);

        // 模拟发短信和邮件：handler = employee_id
        System.out.println("请到【"+msg.getAddress()+"】接回宠物");
        // 省略线下：店铺人员去收回宠物
    }

    private Pet msg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        // salePrice - 市场价上架之前定义
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setState(0);
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }

    private OrderPetAcquisition createOrder(SearchMasterMsg msg, Pet pet, long handler, String note) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(note);
        Date date = new Date(System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000);
        order.setLastcomfirmtime(date);
        order.setPrice(msg.getPrice());
        // payType - 现金支付
        order.setPetId(pet.getId());
        order.setUserId(pet.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(handler);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }
}
